import base64
import datetime
import logging
from flask import Blueprint, render_template, request, jsonify
from bilibili_api import search, sync, video
from exts import db
from models import MonitoringTask, MonitoredVideo, Comment
import requests
import asyncio
from script.spider_common_method import save_video, filter_string, get_all_comment, update_comment, \
    delete_video_comments, \
    re_crawling_video_comments
from utils.CredentialUtil import CredentialConfig

video_bp = Blueprint("video", __name__, url_prefix="/video")


# 视频详情
@video_bp.route('/detail/<bvid>')
def video_detail(bvid):
    video = MonitoredVideo.query.filter_by(bvid=bvid).first()
    comments = []
    for c in Comment.query.filter_by(bvid=bvid, is_violence=False).limit(20).all():
        comments.append(c.content)
    violent_comments = []
    for c in Comment.query.filter_by(bvid=bvid, is_violence=True).limit(20).all():
        violent_comments.append(c.content)
    return render_template('video_detail.html', video=video, comments=comments, violent_comments=violent_comments)


@video_bp.route('/ban/<bvid>')
def video_ban(bvid):
    try:
        video = MonitoredVideo.query.filter_by(bvid=bvid).first()
        video.is_banned = True
        db.session.commit()
        return jsonify({'success': 'success'}), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': 'Failed to ban video'}), 500


@video_bp.route('/unban/<bvid>')
def video_unban(bvid):
    try:
        video = MonitoredVideo.query.filter_by(bvid=bvid).first()
        video.is_banned = False
        db.session.commit()
        return jsonify({'success': 'success'}), 200
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': 'Failed to ban video'}), 500
